//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package mail_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/user_mail_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MailInfoDbItem struct {
	MailId      string `bson:"_id"`
	UserId      string `bson:"userId"`
	FromAccount string `bson:"fromAccount"`
	ToAccount   string `bson:"toAccount"`
	Title       string `bson:"title"`
	TimeStamp   int64  `bson:"timeStamp"`
	HasRead     bool   `bson:"hasRead"`
}

func (item *MailInfoDbItem) ToMailInfo() *user_mail_api.MailInfo {
	return &user_mail_api.MailInfo{
		MailId:      item.MailId,
		UserId:      item.UserId,
		FromAccount: item.FromAccount,
		ToAccount:   item.ToAccount,
		Title:       item.Title,
		TimeStamp:   item.TimeStamp,
		HasRead:     item.HasRead,
	}
}

type _MailInfoDao struct {
	mc *mongo.Collection
}

func newMailInfoDao(db *mongo.Database) (*_MailInfoDao, error) {
	mc := db.Collection(db_ns.DB_NS_MAIL + "mail_info")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"userId", 1}, {"timeStamp", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_MailInfoDao{mc: mc}, nil
}

func (db *_MailInfoDao) Insert(ctx context.Context, dbItem *MailInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_MailInfoDao) Exist(ctx context.Context, userId, mailId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": mailId, "userId": userId})
	return count > 0, err
}

func (db *_MailInfoDao) Get(ctx context.Context, userId, mailId string) (*MailInfoDbItem, error) {
	retItem := &MailInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": mailId, "userId": userId}).Decode(retItem)
	return retItem, err
}

func (db *_MailInfoDao) Remove(ctx context.Context, userId, mailId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": mailId, "userId": userId})
	return err
}

func (db *_MailInfoDao) RemoveById(ctx context.Context, userId string, mailIdList []string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"userId": userId, "_id": bson.M{"$in": mailIdList}})
	return err
}

func (db *_MailInfoDao) UpdateHasRead(ctx context.Context, userId, mailId string, hasRead bool) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": mailId, "userId": userId},
		bson.M{"$set": bson.M{"hasRead": hasRead}})
	return err
}

func (db *_MailInfoDao) Count(ctx context.Context, userId string, filterByHasRead, hasRead bool) (uint32, error) {
	query := bson.M{"userId": userId}
	if filterByHasRead {
		query["hasRead"] = hasRead
	}

	count, err := db.mc.CountDocuments(ctx, query)
	return uint32(count), err
}

func (db *_MailInfoDao) ListForRemove(ctx context.Context, userId string, count int64) ([]string, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"userId": userId},
		options.Find().SetSort(bson.M{"timeStamp": 1}).SetLimit(count).SetProjection(bson.M{"_id": 1}))
	if err != nil {
		return nil, err
	}
	tmpList := []*MailInfoDbItem{}
	err = cursor.All(ctx, &tmpList)
	if err != nil {
		return nil, err
	}
	retList := []string{}
	for _, item := range tmpList {
		retList = append(retList, item.MailId)
	}
	return retList, nil
}

func (db *_MailInfoDao) List(ctx context.Context, userId string, filterByHasRead, hasRead bool, offset, limit int64) ([]*MailInfoDbItem, error) {
	query := bson.M{"userId": userId}
	if filterByHasRead {
		query["hasRead"] = hasRead
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}

	retList := []*MailInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
